<?php
class importAction extends backendAction{
    

   
    /**
     * 上传excel导入 指标
     *  指标 导入
     */ 
    public function importTarget(){
		$user = getUserSession();
		
        if(count($_FILES) > 0){
    		//is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的
			if(is_uploaded_file($_FILES["excel"]["tmp_name"])){ 				
				$file = $_FILES["excel"]["tmp_name"];				
				if(is_file($file)){
					$res = excelToArray($file);
					
					if(isset($res[0]['厅店']) && $user['roleId'] == 4)
					{
						//督导导入厅店指标
						D('target')->importStoreTarget($res);
					}
					elseif(isset($res[0]['县区']) && $user['roleId'] == 3)
					{
						//市场总监导入县区指标
						D('target')->importMicroAreaTarget($res);
					}
					elseif(isset($res[0]['地市']) && $user['roleId'] == 1)
					{
						//超级管理员导入城市指标
						D('target')->importCityTarget($res);
					}
                   $this->ajaxReturn(1, L('operation_success'));
				}
			}else{
				$this->ajaxReturn(0, L('placeUploadFile'));	
			}
    	}else{
    		$this->ajaxReturn(0, L('placeUploadFile'));	
    	}          
        
    }
    


    
    /**
     * 厅店导入
     * 张名尊，20140505;
     */ 
     public function importStore(){
         if(count($_FILES) > 0){
    		//is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的
			if(is_uploaded_file($_FILES["excel"]["tmp_name"])){ 				
				$file = $_FILES["excel"]["tmp_name"];				
				if(is_file($file)){
					//读取文件内容
					$res = readExcelFile($file);
					if(is_array($res)){
                        //print_r($res);exit();
                        //准备数据 
                        //1、地区
                        $regionList = D('region')->cate_cache();
                        $regionList = $regionList['l'];
                        //2、商圈  格式 id=>name
                        $bcList = D('bc')->cate_cache();
                        //3、客户 格式 id=>name
                        $customerList = D('customer')->cate_cache();
                        //4、渠道 
                        $channelList = array(
                            '社会渠道'=>2,
                            '自有渠道'=>1,
                        );
                        //5、保存数据的数组
                        $data = $error = array();
                        foreach($res as $rk=>$rv){
                            $temp = array();
                            $flag = false;
                            foreach($rv as $rkk=>$rvv){
                                $temp[trim($rkk)] = trim($rvv);
                                if(empty($rvv)){
                                    $error[$rk]['message'] = '导入失败，部分数据为空';
                                    $flag = true;
                                }
                            }
                            if($flag){
                                continue;
                            }
                            $rv = $temp;
                            //地区
                             $regArr = $this->regionVerify($regionList,$rv['大区'],$rv['地市'],$rv['片区'],1);   
                             if(empty($regArr['microAreaId'])){
                                $error[$rk]['message'] = '导入厅店 '.$rv['厅店名称'].'失败：片区 '.$rv['片区'].'在数据库中没有找到或者新增插入失败';
                                unset($data[$rk]);
                                break;  
                             }
                             //商圈
                             $bcArr = bcVerify($bcList,$rv['商圈名称'],$rv['商圈级别'],1);
                             if($bcArr['bcId']){
                                $data[$rk]['bcId'] = $bcArr['bcId'];
                             }else{
                                $error[$rk]['message'] = $bcArr['error'];
                                unset($data[$rk]);
                                break;
                             }
                             //客户
                             $customerArr = customerVerify($customerList,$rv['渠道客户名称'],1);
                             if($customerArr['customerId']){
                                $data[$rk]['customerId'] = $customerArr['customerId'];
                             }else{
                                $error[$rk]['message'] = $customerArr['error'];
                                unset($data[$rk]);
                                continue;                                
                             } 
                                              
                             $data[$rk]['regionId'] = $regArr['microAreaId'];
                             $data[$rk]['ctms'] = $rv['厅店CTMS编码'];
                             $data[$rk]['address'] = $rv['详细地址'];
                             $data[$rk]['isHaveTaste'] = $rv['是否有体验台']=='是'?1:0;
                             $data[$rk]['channel'] = $channelList[$rv['渠道']];
                             $data[$rk]['name'] = $rv['厅店名称'];
                        }
                        $this->insertData($data,$error,'store');
                    }
                }
            }
        }
     }
     
     /**
      * 导入机型信息
      */ 
     public function importModelInfo(){
        if(count($_FILES) > 0){
    		//is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的
			if(is_uploaded_file($_FILES["excel"]["tmp_name"])){ 				
				$file = $_FILES["excel"]["tmp_name"];				
				if(is_file($file)){
					//读取文件内容
					$res = readExcelFile($file);
                    //var_dump($res);exit();
                    if(is_array($res) && !empty($res)){
                        $fileArr = array(
                            '机型'=>'modelName',
                            '销售价格'=>'salesPrice',
                            '产品参数'=>'product',
                            '单台提成'=>'singleRoyalty',
                            '功能亮点'=>'highlights',
                        );
                        foreach($res as $k=>$v){
                            foreach($v as $kk=>$vv){
                                if(empty($vv)){
                                    continue;
                                }
                                $tempV[$fileArr[$kk]] = $vv;
                            }
                            $vv = $tempV;
                            if($data = D('modelInfo')->create($vv)){
                                $data['addTime'] = time();
                                $data['addUserId'] = $_SESSION[C('user_session_name')]['id'];
                            }
                            $opptRes = D('modelInfo')->add($data,array(),1);
                            if($opptRes){
                               $this->ajaxReturn(1, L('operation_success'));	
                            }else{
                               $this->ajaxReturn(0, L('operation_failure'));
                            }                             
                        }
                        
                    }
                }
            }
        }        
        
     }
     
     /**
      * 导入 门店活动
      *  张名尊，20140512
      * 
      */ 
     public function importPromotion(){
        
        //定义字段
        $fileArr = array(
            '活动主题：'=>'theme',
            '活动地点：'=>'sotreId',
            '活动开始时间：'=>'startTime',
            '活动结束时间：'=>'endTime',
            '地址：'=>'address',
            '活动组织人：'=>'organizer',
            '活动内容：'=>'content',     
            '临促数量：'=>'salerNum',
            '临促工资：'=>'salerPay',
            '临促费用：'=>'salerTotalPay',
        );
        
        $file = $_FILES["excel"]["tmp_name"];
    	if(!is_file($file)) return false;
    	import('@.ORG.Excel.ExcelReader');
    	$reader = new Spreadsheet_Excel_Reader($file, false, '');
    	$res = $reader->sheets[0]['cells'];unset($reader);
        $data = $error = array();
        $regionList = D('region')->cate_cache();
        foreach($res as $k=>$v){
            sort($v);
            foreach($v as $kk=>$vv){
                if(!empty($vv) && isset($fileArr[$vv])){
                    switch($vv){
                        case '活动地点：':
                            $region = $v[$kk+1];
                            $region = explode('：',$region);
                            $region  = $region[1];
                            $region = $this->regionVerify($regionList,0,0,$region,0);
                            if(!$arr['microAreaId']){
                               $error[0]['message'] = '导入活动 失败：片区 '.$region.'在数据库中没有找到';
                               break 3;
                            }
                            $store = $v[$kk+2];
                            $store = explode('：',$store);
                            $store  = $store[1]; 
                            $id = M('store')->where(array('name'=>$store))->getField('id');
                            if(!$id){
                               $error[0]['message'] = '导入活动 失败：厅店 '.$store.'在数据库中没有找到';
                               break 3;                                
                            }else{
                                $data['storeId'] = $store;
                            }
                            $data['address'] = $v[$kk+3];
                            break;
                          case '活动开始时间：':
                                $data['startTime'] = strtotime($v[$kk+1]);
                            break;
                          case '活动结束时间：':
                                $data['endTime'] = strtotime($v[$kk+1]);
                            break;                            
                        defaul:
                          $data[$fileArr[$vv]] = $v[$kk+1];  
                          break;
                    }
                }
            }
        }
        var_dump($data);
        $this->insertData(array(0=>$data),$error,'promotion');
    
     }
     
     
     private function getExcel(){
         if(count($_FILES) > 0){
    		//is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的
			if(is_uploaded_file($_FILES["excel"]["tmp_name"])){ 				
				$file = $_FILES["excel"]["tmp_name"];				
				if(is_file($file)){
					//读取文件内容
					$res = readExcelFile($file);
                }
            }
        }
        return $res;
     }
     
     /**
      * 导入业绩展示
      * 张名尊，20140526
      */ 
     public function importUserSales(){
        
        $res = $this->getExcel();
        
        if(!empty($res)){
            $fileArr = array(
                '营业厅'=>'storeName',
                '促销员'=>'name',
                '月销量（台）'=>'monthSales',
                '月重点销量（台）'=>'monthSalesByMain',
            ); 
            $data = $error = array();         
            foreach($res as $k=>$v){
                foreach($v as $kk=>$vv){
                    $data[$k][$fileArr[$kk]]=$vv;
                }
                
            }
            $this->insertData($data,$error,'userSales');
        }
     }
     
     
     /**
      * 导入通讯录
      * 
      */ 
     
     public function importUserInfo(){
     	import('@.ORG.Excel.ExcelReader');
    	$reader = new Spreadsheet_Excel_Reader($_FILES["excel"]["tmp_name"], false, 'utf-8');
        $fileArr = array(
            '2'=>'employment',
            '3'=>'source',
            '4'=>'department',
            '5'=>'userName',
            '6'=>'position',
            '7'=>'phone',
            '8'=>'email',  
        );
        
        $count = count($reader->sheets);
        $data = $error = array();
        for($i=0;$i<$count;$i++){
            $res = $reader->sheets[$i]['cells'];
            //var_dump($reader->data);
            //exit();
            foreach($res as $k=>$v){
          
                if(!is_numeric($v[1])){
                    continue;
                }
                //unset($v[1]);
                foreach($v as $kk=>$vv){
                    if(isset($fileArr[$kk])){
                        $temp[$fileArr[$kk]] = $vv;
                    }
                }
                $data[] = $temp;
            }
        }
          // print_r($data);exit();    
          $this->insertData($data,$error,'import_user_info');
        
     }
     
     
     /**
      * 最终入库及错误日志记录
      * 张名尊，20140506
      */ 
     private function insertData($data,$error,$tableName){
         $opptRes = false;
         $admin = getUserSession();
         if(!empty($data)){
             sort($data);
             $opptRes = D($tableName)->addAll($data,$options=array(),$replace=true);
             if(!$opptRes){
                $error[]['message']= '导入失败： 插入数据库错误'.mysql_error();
             }
         }
         if(!empty($error)){
            foreach($error as $ek=>$ev){
                $error[$ek]['modular'] = $tableName;
                $error[$ek]['importTime'] = time();
                $error[$ek]['importUser'] = $admin['id'];
                $error[$ek]['importUserRealName'] = $admin['realName'];
            }
            sort($error);
            D('import_data_error')->addAll($error);
         }
         if($opptRes){
            $this->ajaxReturn(1, L('operation_success'));	
         }else{
            $this->ajaxReturn(0, L('operation_failure'));
         }        
        
     }
    /**
     * 验证商圈是否存在,并且可插入不存在的记录
     */ 
      private function bcVerify(&$bcList,$name,$regionId,$bcLevel,$isInsert){
         //商圈
         $bcId = array_search($name,$bcList);
         if($bcId===false && $isInsert){
            $bcInsertId = M('bc')->add(array('name'=>$name,'regionId'=>$regionId,'level'=>$bcLevel));
            if(!$bcInsertId){
              $error  = '导入 失败：商圈 '.$name.'在数据库中没有找到且新增插入失败'; 
            }else{
               $bcList[$bcInsertId] = $name;
               $bcId = $bcInsertId;
            }
         }  
         return array('bcId'=>$bcId,'error'=>$error);     
        
      }
      
     /**
     * 验证客户是否存在,并且可插入不存在的记录
     */ 
      private function customerVerify(&$customerList,$name,$isInsert){
         //商圈
         $customerId = array_search($name,$customerList);
         if($customerId===false && $isInsert){
            $customerInsertId = M('customer')->add(array('name'=>$name));
            if(!$customerInsertId){
              $error  = '导入 失败：客户 '.$name.'在数据库中没有找到且新增插入失败'; 
            }else{
               $customerList[$customerInsertId] = $name;
               $customerId = $customerInsertId;
            }
         }  
         return array('customerId'=>$customerId,'error'=>$error);     
      }     
          
     
     /**
      *  验证片区是否存在，并且可插入不存在的记录
      *  $microAreaName 片区
      *  $cityName 地市
      *  $areaName 大区
      *  $isInsert 是否增加插入
      */ 
     private function regionVerify(&$regionList,$areaName=0,$cityName=0,$microAreaName=0,$isInsert){
        if(empty($microAreaName)){
            return false;
        }
        //var_dump($regionList);
        $arr = array();
        foreach($regionList as $v){
            if($v['name']==$microAreaName){
                $arr['microAreaId'] = $v['id'];
            }
            if($v['name']==$cityName){
               $arr['cityId'] = $v['id']; 
            }
            if($v['name']==$areaName){
               $arr['areaId'] = $v['id']; 
            }
        }
        if($isInsert && !empty($areaName) && !empty($cityName) && !empty($microAreaName)){
            //不存在才更新           
            if(empty($arr['microAreaId'])){
                if(empty($arr['cityId'])){
                    if(empty($arr['areaId'])){
                         //插入大区
                        $newData = $this->insertRegion($regionList,0,0,$areaName);    
                        $arr['areaId'] = $newData['id'];                    
                         //插入地市
                        $newData = $this->insertRegion($regionList,1,$arr['areaId'],$cityName);
                        $arr['cityId'] = $newData['id'];
                        //插入片区
                        $newData = $this->insertRegion($regionList,2,$arr['cityId'],$microAreaName);
                        $arr['microAreaId'] = $newData['id'];                       
                        
                    }else{
                        //插入地市
                        $newData = $this->insertRegion($regionList,1,$arr['areaId'],$cityName);
                        $arr['cityId'] = $newData['id'];
                        //插入片区
                        $newData = $this->insertRegion($regionList,2,$arr['cityId'],$microAreaName);
                        $arr['microAreaId'] = $newData['id'];
                    }   
                }else{
                    //插入片区
                    $newData = $this->insertRegion($regionList,2,$arr['cityId'],$microAreaName);
                    $arr['microAreaId'] = $newData['id'];
                }
            }
            
        }
        return $arr;
     }
     
     /**
      * 插入地区
      * 
      */ 
     private function insertRegion(&$regionList,$level,$pid,$name){         
        $newData = array();
        $newData['pid'] = $pid;
        $pspid = $regionList[$newData['pid']]['spid'];
        if ($pspid) {
            $spid = $pspid . $pid . '|';
        } else {
            $spid = $pid . '|';
        }   
        $newData['spid'] = $spid;
        $newData['name']=$name;
        $newData['level'] = $level;
        $addRes = D('region')->add($newData);
        if($addRes){
           $newData['id'] = $arr['microAreaId'] = $addRes; 
           $regionList[$addRes] = $newData;
        }else{
            $newData['id'] = 0;
        }        
        return $newData;
     }
     
     
    
}







?>